package org.droidcon.apps.template.ui;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.droidcon.apps.template.R;
import org.droidcon.apps.template.provider.ProfileContract;
import org.droidcon.apps.template.provider.ProfileDatabase;
import org.droidcon.apps.template.util.UIUtils;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Data;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Save the user's profile data for exchange with other conference visitors.
 * 
 * @author henning
 * 
 */
public class ProfileActivity extends Activity {

	public static final String TAG = ProfileActivity.class.getSimpleName();
	private static final int REQUEST_CODE_PICK_CONTACT = RESULT_FIRST_USER + 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_profile);
		//((TextView) findViewById(R.id.title_text)).setText(getTitle());

		findViewById(R.id.profile_btn_clear).setOnClickListener(clickListener);
		findViewById(R.id.profile_btn_save).setOnClickListener(clickListener);

		database = new ProfileDatabase(getApplicationContext(),
				ProfileContract.DATABASE_NAME, null,
				ProfileContract.DATABASE_VERSION);

		if (!database.haveOwnProfile()) {
			return;
		}

		ContentValues values = database.getMyProfile();

		EditText theView = null;
		String theContent = null;

		theView = (EditText) findViewById(R.id.profile_entry_name_last);
		theContent = (String) values.get(ProfileContract.COLUMN_NAME_LAST);
		theView.setText(theContent);

		theView = (EditText) findViewById(R.id.profile_entry_name_first);
		theContent = (String) values.get(ProfileContract.COLUMN_NAME_FIRST);
		theView.setText(theContent);

		theView = (EditText) findViewById(R.id.profile_entry_company_name);
		theContent = (String) values.get(ProfileContract.COLUMN_COMPANY_NAME);
		theView.setText(theContent);

		theView = (EditText) findViewById(R.id.profile_entry_googlemarket_account);
		theContent = (String) values
				.get(ProfileContract.COLUMN_MARKET_DEVELOPER_ACCOUNT);
		theView.setText(theContent);

		theView = (EditText) findViewById(R.id.profile_entry_ticket_nr);
		theContent = (String) values
				.get(ProfileContract.COLUMN_DROIDCON_TICKET_NUMBER);
		theView.setText(theContent);

		theView = (EditText) findViewById(R.id.profile_entry_id);
		theContent = (String) values.get(ProfileContract.KEY_ID);
		theView.setText(theContent);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	OnClickListener clickListener = new OnClickListener() {
		public void onClick(View view) {
			Log.i(TAG, "ID is: " + view.getId());
			int id = view.getId();
			if (id ==  R.id.profile_btn_clear){
				onClearClick(view);
			} else if (id == R.id.profile_btn_save){
				onSaveClick(view);				
			}
		}
	};
	private ProfileDatabase database;
	private Uri mMyContactDetails;

	/**
	 * Save the entry currently in the form
	 * 
	 * @param v
	 */
	public void onSaveClick(View view) {
		Log.d(TAG, "saveclick");

		ContentValues values = new ContentValues();

		values.put(ProfileContract.COLUMN_COMPANY_NAME,
				((TextView) findViewById(R.id.profile_entry_company_name))
						.getText().toString());

		values.put(ProfileContract.COLUMN_DROIDCON_TICKET_NUMBER,
				((TextView) findViewById(R.id.profile_entry_ticket_nr))
						.getText().toString());

		values.put(
				ProfileContract.COLUMN_MARKET_DEVELOPER_ACCOUNT,
				((TextView) findViewById(R.id.profile_entry_googlemarket_account))
						.getText().toString());

		values.put(ProfileContract.COLUMN_NAME_FIRST,
				((TextView) findViewById(R.id.profile_entry_name_first))
						.getText().toString());

		values.put(ProfileContract.COLUMN_NAME_LAST,
				((TextView) findViewById(R.id.profile_entry_name_last))
						.getText().toString());

		database.saveProfile(values,
				((TextView) findViewById(R.id.profile_entry_id)).getText()
						.toString());

	}

	/**
	 * Clear the saved profile data.
	 * 
	 * @param view
	 */
	public void onClearClick(View view) {
		database.clearProfile();
	}

	public void onPickMyContactData(View view) {
		Intent intent = new Intent(Intent.ACTION_PICK,
				ContactsContract.Contacts.CONTENT_VCARD_URI);
		startActivityForResult(intent, REQUEST_CODE_PICK_CONTACT);

	}

	public void onViewMyContactData(View view) {
		Intent intent = new Intent(Intent.ACTION_VIEW, mMyContactDetails);
		
		intent = new Intent("com.google.zxing.client.android.ENCODE");
		intent.putExtra("ENCODE_TYPE", "CONTACT_TYPE");
		Bundle bundle = new Bundle();
		bundle.putString(ContactsContract.Intents.Insert.NAME, "Jenny");
		bundle.putString(ContactsContract.Intents.Insert.PHONE, "8675309");
		bundle.putString(ContactsContract.Intents.Insert.EMAIL,
				"jenny@the80s.com");
		bundle.putString(ContactsContract.Intents.Insert.POSTAL,
				"123 Fake St. San Francisco, CA 94102");
		intent.putExtra("ENCODE_DATA", bundle);

		intent = new Intent(Intent.ACTION_SEND, mMyContactDetails);
		startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_PICK_CONTACT) {
			if (resultCode == RESULT_OK) {
				mMyContactDetails = data.getData();
				if ((data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION) == Intent.FLAG_GRANT_READ_URI_PERMISSION) {

					Log.v(TAG, data.getDataString());

					Cursor cur = getContentResolver().query(data.getData(),
							null, null, null, null);
					cur.moveToFirst();
					String name = cur
							.getString(cur
									.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					String lookupKey = cur
							.getString(cur
									.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
					Log.v(TAG, name + " " + lookupKey);
					Uri uri = Uri.withAppendedPath(
							ContactsContract.Contacts.CONTENT_VCARD_URI,
							lookupKey);
					Log.v(TAG, uri.toString());
					try {
						AssetFileDescriptor fd = this.getContentResolver()
								.openAssetFileDescriptor(uri, "r");
						FileInputStream fis = fd.createInputStream();
						BufferedReader r = new BufferedReader(new InputStreamReader(fis));
						StringBuilder total = new StringBuilder();
						String line;
						while ((line = r.readLine()) != null) {
						    total.append(line);
						}
						Log.v(TAG, total.toString());
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				updatePickLabel(true);
			}
		}
	}

	private void updatePickLabel(boolean contactPicked) {
		View btnViewContact = findViewById(R.id.profile_btn_view_contact);
		if (contactPicked) {
			btnViewContact.setVisibility(View.VISIBLE);
		} else {
			btnViewContact.setVisibility(View.GONE);
		}

	}

	/** Handle "share" title-bar action. */
	public void onShareClick(View v) {
		final String shareString = getString(R.string.share_template,
				"the additional features", "in the app");

		final Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_TEXT, shareString);

		startActivity(Intent.createChooser(intent,
				getText(R.string.title_share)));
	}

	
}
